<?php
 /**
 * This is a amfphp-service for Press Track System 
 *  
 * @copyright  Copyright (c) 2010-2011 Victor Magarlamov 
 * @version    1.0
 * @link       http://redmine.shelek.su/projects/presstrack
 */

require_once "vo/presstrack/UserClass.php";
require_once "vo/presstrack/PayerClass.php";
require_once "vo/presstrack/PaperClass.php";
require_once "vo/presstrack/ReportGeneralClass.php";
require_once "vo/presstrack/ReportSaleClass.php";
require_once "vo/presstrack/ReportPaymentClass.php";
require_once "vo/presstrack/ReportOperationClass.php";
require_once "vo/presstrack/TrackClass.php";
require_once "vo/presstrack/vos/CreateOrderResultVO.php";
require_once "vo/presstrack/vos/AddPartResultVO.php";
require_once "vo/presstrack/vos/GetTrackerResultVO.php";
 
require_once "vo/presstrack/OrderClass.php";
require_once "vo/presstrack/OperationClass.php";

require_once "vo/presstrack/PressTargetVO.php";
require_once "vo/presstrack/vos/StatisticResultVO.php";
require_once "vo/presstrack/StatisticVO.php";


 /**
 * PressTrack class 
 *
 * @author Victor Magarlamov <victor.magarlamov@gmail.com>
 * @version 1.0
 * @package PressTrack
 */
 
class PressTrack
{
	function PressTrack() 
	{
		//require_once ('W:WWW\Doc_For_All\www\press_track_config.php');
		//include("PressTrack.methodTable.php");
		mysql_pconnect('127.0.0.1', 'root', 'VNt3ks');
		mysql_query("SET CHARACTER SET 'utf8'"); 	
		mysql_query("SET NAMES 'utf8'");
		mysql_select_db('press_track_new');				
    }
	
	/**
	 * LoginUser
	 *	 
     * calls static user authorisation method 
	 *
	 * :WARNING: Don't forget to set access to section when adding new user 
	 *
	 * @param	string			$name	nickname
	 * @param	string			$pas	password
	 * @param	string			$sec	section	 
     * @return	LoginResultVO	$result
     */
	function LoginUser($name, $pas, $sec) 
	{
		$result = UserClass::Login($name, $pas, $sec);
		return $result;
	}
	
	function AddWorker($nick, $pass, $fullname, $section) 
	{
		$result = UserClass::AddWorker($nick, $pass, $fullname, $section);
		return $result;
	}
	
	function SetAccess($iduser, $section)
	{
		$result = UserClass::SetAccess($iduser, $section);
		return $result;
	}
	
	/**
	 * AddOrder
	 *	 
     * write new order into database 
	 *
	 * :WARNING: Id of Product's Template
	 *  
	 * 		- 99	- default, 
	 * 		- 1		- card, 
	 * 		- 2		- flyer, 
	 * 		- 3		- poster, 
	 * 		- 4		- leaflet, 
	 * 		- 5 	- eurobooklet
	 * 		- 6 	- magazine, 
	 * 		- 7 	- catalog, 
	 * 		- 8 	- newspaper, 
	 * 		- 9 	- book, 
	 * 		- 10 	- stanz, 
	 * 		- 11 	- trio
	 *
	 * @param	int					$manager 	id of manager
	 * @param	int					$template	id of product's template
	 * @return	CreateOrderResultVO	$result
     */
	function AddOrder($manager, $template)
    {
		$creationResult 		= new CreateOrderResultVO();		
		$order 					= new OrderClass("", $manager, $template);
		$creationResult->order	= $this->GetOrder($order->iOrderId);
		$creationResult->status	= true;		
		return $creationResult;
	}
	
	/**
	 * GetOrder
	 *	 
     * read one order from database 
	 *
	 * :WARNING: 
	 *
	 * If the first argument to OrderClass's constructor is not empty - 
	 * order will be Read From Database
	 * Else if If the first argument to constructor is empty - 
	 * order will be Write To Database (see "AddOrder" method)
	 *
	 * @param	int			$order id
	 * @return	OrderClass	$order
     */
	function GetOrder($idorder) 
	{
		$order = new OrderClass($idorder, "", "");	
		return $order;
	}
	
	/**
	 * GetOrders
	 *	 
     * read a few orders from database 
	 *
	 * @param	int		$orders by id of manager
	 * @param	string	$current orders only or store orders only or all orders
	 * @param	int		$orders by year
	 * @return	array	$ArrayOfData
     */
	function GetOrders($iduser, $table, $year) 
	{
		set_time_limit(0);
		
		switch ($table) {
			case "cur_orders":
				if($iduser == -1)
				{
					$sql = "SELECT idorder FROM press_track_new.order " 
						 . "WHERE press_track_new.order.state != 4";
				} 
				else 
				{
					$sql = "SELECT idorder FROM press_track_new.order "
						 . "WHERE press_track_new.order.state != 4 "
						 . "AND press_track_new.order.manager = $iduser";
				}
			break;
			
			case "store_orders":
				$sql = "SELECT idorder FROM press_track_new.order " 
					 . "WHERE creation LIKE '%$year' "						
					 . "AND press_track_new.order.state = 4 "
					 . "AND press_track_new.order.manager = $iduser";
			break;
			
			case "all":
				$sql = "SELECT idorder FROM press_track_new.order "
					 . "WHERE LOCATE($year, press_track_new.order.creation, 6)";
			break;
		}
		
		$query = mysql_query($sql);		
		if (mysql_errno()) return mysql_errno() . " : " . mysql_error();		
		
		while ($res = mysql_fetch_object($query)) 
		{
			$order =  new OrderClass($res->idorder, "", "");
			$ArrayOfData[] = clone (object) $order;
		}	
		return $ArrayOfData;
	}
	
	/**
	 * GenerateLabelForOrder
	 *	 
     * find and return not occupied label
	 *
	 * @return	int	$label for order
     */
	function GenerateLabelForOrder()
	{
		$label = OrderClass::GenerateLabel();
		return $label;
	}
	
	/**
	 * UpdateOrder
	 *	 
     * new value into order's parametr
	 *
	 * @param	int		$id of order
	 * @param	string	$order's param
	 * @param	string	$new value
	 * @return	string	$result "successful" or error message
     */
	function UpdateOrder($idorder, $param, $value) 
	{
		$result = OrderClass::UpdateOrder($idorder, $param, $value);
		return $result;
	}	
	
	/**
	 * CalculateCostOfOrder
	 *	 
     * calculate cost of all tasks in the order
	 *
	 * :TODO: add mode - calc by time & calc by price
	 *
	 * @param	int						$idorder	id of order
	 * @return	CalcCostOfOrderResultVO	$result
     */
	function CalculateCostOfOrder($idorder) 
	{
		$result = OrderClass::CalculateCost($idorder);
		return $result;
	}
	
	/**
	 * CalculateDebtOfOrders
	 *	 
     * calculate debt every order
	 *
	 * @return	string	$result	"successful" or error message
     */
	function CalculateDebtOfOrders() 
	{
		$result = OrderClass::CalculateDebtForOrders();			
		return $result;
	}
	
	/**
	 * CopyOrder
	 *	 
     * write to database copy of a order
	 *
	 * @param	int					$idorder id of order
	 * @return	CreateOrderResultVO	$result 
     */
	function CopyOrder($idorder)
	{
		$creationResult = OrderClass::CopyOrder($idorder);
		return $creationResult;
	}	
	
	/**
	 * RemoveOrder
	 *	 
     * delete a order from database 
	 *
	 * :TODO: change foreign key for payment - don't delete order if payment is
	 *
	 * @param	int	$idorder id of a order
     */
	function RemoveOrder($idorder) 
	{
		$sql = sprintf("DELETE FROM press_track_new.order WHERE press_track_new.order.idorder = %d", $idorder);
		$query = mysql_query($sql);
	}
	
	/**
	 * AddGroup
	 *	 
     * create a new group of products and task for a order 
	 *
	 * @param	int				$idorder	id of a order
	 * @return	AddPartResultVO	$result 
     */
	function AddGroup($idorder) 
	{
		$order	= new OrderClass($idorder, "", "");
		$order->AddGroup("визитка");
		
		$result			= new AddPartResultVO();
		$result->part	= $order->GetGroup($order->iGroupNum);
		$result->status	= true;
		return $result;
	}
	
	/**
	 * RemoveGroup
	 *	 
     * delete a group of products and task from a order 
	 *
	 * @param	int		$idorder		id of a order
	 * @param	int		$index_group	index of a group
	 * @return	string	$result 		"successful" or error message
     */
	function RemoveGroup($idorder, $index_group)
	{
		$order	= new OrderClass($idorder, "", "");
		$result = $order->RemoveGroup($index_group);
		return $result;
	}
	
	/**
	 * AddProduct
	 *	 
     * add new product into order's group 
	 *
	 * @param	int					$idorder		id of a order
	 * @param	int					$index_group	index of a group
	 * @param	string				$label			product's label
	 * @param	int					$run			product's run
	 * @param	string				$size			product's size
	 * @param	color				$color			product's color
	 * @return	AddProductResultVO	$result		
     */
	function AddProduct($idorder, $index_group, $label, $run, $size, $color)
    {
		$result = OrderClass::AddProduct($idorder, $index_group, $label, $run, $size, $color);
		return $result;		
	}
	
	/**
	 * UpdateProduct
	 *	 
     * update product's parameter 
	 *
	 * @param	int		$idproduct	product ID
	 * @param	string	$param		name of parameter
	 * @param	string	$value		new value
	 * @return	string	$result		"successful" or error message
     */
	function UpdateProduct($idproduct, $param, $value) 
	{
		$result = OrderClass::UpdateProduct($idproduct, $param, $value);
		return $result;
	}
	
	/**
	 * RemoveProduct
	 *	 
     * remove product from group
	 *
	 * @param	int		$idproduct	product ID
	 * @return	string	$result		"successful" or error message
     */
	function RemoveProduct($idproduct) 
	{
		$result = OrderClass::RemoveProduct($idproduct);
		return $result;
	}
	
	/**
	 * AddTask
	 *	 
     * add new task into order's group 
	 *
	 * @param	int		 			$idorder		id of a order
	 * @param	int					$index_group	index of a group
	 * @param	string				$label			name of operation
	 * @param	string				$value			value of operation
	 * @param	int					$section		section ID
	 * @return	AddTaskResultVO		$result		
     */
	function AddTask($order, $index_group, $label, $value, $section)
    {
		$result = OrderClass::AddTask($order, $index_group, $label, $value, $section);
		return $result;		
	}
	
	/**
	 * UpdateTask
	 *	 
     * update task's parameter 
	 *
	 * @param	int		$idtask		task ID
	 * @param	string	$param		name of parameter
	 * @param	string	$value		new value
	 * @return	string	$result		"successful" or error message
     */
	function UpdateTask($idtask, $param, $value)
	{
		$result = OrderClass::UpdateTask($idtask, $param, $value);
		return $result;
	}
	
	/**
	 * RemoveTask
	 *	 
     * remove task from group
	 *
	 * @param	int		$idtask		task ID
	 * @return	string	$result		"successful" or error message
     */
	function RemoveTask($idtask) 
	{
		$result = OrderClass::RemoveTask($idtask);
		return $result;
	}
	
	/**
	 * AddRelation
	 *	 
     * setting relation between product and task 
	 *
	 * @param	int	$idproduct	product ID
	 * @param	int	$idtask		task ID
	 * @return	int	$result		relation ID
     */
	function AddRelation($idproduct, $idtask)
    {
		$result = OrderClass::AddRelation($idproduct, $idtask);
		return $result;
	}
	
	/**
	 * RemoveRelation
	 *	 
     * remove relation between product and task
	 *
	 * @param	int		$relation	relation ID
	 * @return	string	$result		"successful" or error message
     */
	function RemoveRelation($idrelation) 
	{
		$result = OrderClass::RemoveRelation($idrelation);
		return $result;		
	}
	
	/**
	 * GetPayers
	 *	 
     * read payers from database 
	 *
	 * @return	array	$result		
     */
	function GetPayers() 
	{
		$result = PayerClass::GetPayers();
		return $result;
	}
	
	/**
	 * AddPayment
	 *	 
     * add pyment from order's customer
	 *
	 * @param	int			$idorder	order ID
	 * @param	string		$creation	date of payment creation
	 * @param	string		$account	number of payment
	 * @param	double		$sum		sum
	 * @param	string		$note		note
	 * @return	int/string	$result		idpayment or error message
     */
	function AddPayment($idorder, $creation, $account, $sum, $note) 
	{
		$result = OrderClass::AddPayment($idorder, $creation, $account, $sum, $note);		
		return $result;
	}
	
	function GetPayments($user_id, $year) 
	{
		if ($user_id == -1) 
		{
			$sql = sprintf("SELECT * FROM press_track_new.payment "
				 . "WHERE LOCATE($year, press_track_new.payment.creation, 6)");
		}
		else
		{
			$sql = sprintf("SELECT * FROM press_track_new.payment "
				 . "WHERE LOCATE($year, press_track_new.payment.creation, 6) "
				 . "AND payment.order IN (SELECT idorder FROM press_track_new.order "
				 . "WHERE customer = $user_id)");
		}
		$query = mysql_query($sql);		
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		
		while ($payment = mysql_fetch_object($query)) 
		{
			if ($user_id == -1) 
			{
				$sql = "SELECT iduser as customer_id, name as customer_name "
					 . "FROM press_track_new.user WHERE iduser IN( "
					 . "SELECT customer FROM press_track_new.order "
					 . "WHERE idorder = $payment->order)";
			}
			else
			{
				$sql = "SELECT iduser as customer_id, name as customer_name "
					 . "FROM press_track_new.user WHERE iduser = $user_id";
			}
			
			$query2 = mysql_query($sql);
			$res = mysql_fetch_object($query2);
			$payment->customer_name = $res->customer_name;
			$payment->customer_id = $res->customer_id;
			
			$sql = sprintf("SELECT label as order_label FROM press_track_new.order "
				 . "WHERE idorder = $payment->order");
			$query2 = mysql_query($sql);
			$res = mysql_fetch_object($query2);
			$payment->order_label = $res->order_label;
			
			$result[] = $payment;
		}
		return $result;
	}
	
	function UpdatePayment($idpayment, $order, $creation, $account, $sum, $note) 
	{
		$sql = sprintf("UPDATE press_track_new.payment SET press_track_new.payment.order = %d, press_track_new.payment.creation = '%s', press_track_new.payment.account = '%s', press_track_new.payment.note = '%s' WHERE press_track_new.payment.idpayment = %d", $order, $creation, $account, $note, $idpayment);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		// дописать обновление суммы с учетом разницы.
		$sql = sprintf("SELECT press_track_new.payment.sum AS old_pay FROM press_track_new.payment WHERE press_track_new.payment.idpayment = %d", $idpayment);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$pay = mysql_fetch_object($query);
		$val = $sum - $pay->old_pay; 
		
		$sql = sprintf("UPDATE press_track_new.order SET debt = debt - %d WHERE press_track_new.order.idorder = %d", $val, $order);
		$query = mysql_query($sql);
		
		$sql = sprintf("UPDATE press_track_new.payment SET press_track_new.payment.sum = %f WHERE press_track_new.payment.idpayment = %d", $sum, $idpayment);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		else return "successful";
	}
	
	function RemovePayment($idpayment) 
	{
		$sql = sprintf("DELETE FROM press_track_new.payment WHERE idpayment = %d", $idpayment);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();	
		else return "successful"; 
	}
	
	/**
	 * AddCustomer
	 *	 
     * insert new customer
	 *
	 * @param	int	$medium	the ID of the manager who is the mediator for a new customer
	 * @return	int	$iduser	the ID of the new customer
     */
	function AddCustomer($medium) 
	{
		$iduser = UserClass::AddCustomer($medium);
		return $iduser;
	}
	
	/**
	 * GetCustomers
	 *	 
     * read customers from database 
	 *
	 * :WARNING: 
	 *
	 * if you want get all data about customers (without filter by manager) -
	 * change the "$manager" to "-1"
	 *
	 * @param	int		$manager	filter customers by the mediator
	 * @param	int		$year		filter customer's statistic by year
	 * @return	array	$result		
     */
	function GetCustomers($manager, $year) 
	{
		$ar_customers = UserClass::GetCustomers($manager, $year);
		return $ar_customers;
	}
	
	/**
	 * UpdateUser
	 *	 
     * insert new customer
	 *
	 * @param	int		$iduser	the ID of the user
	 * @param	string	$param	name of the parameter
	 * @param	string	$value	new value
	 * @return	string	$result	"successful" or error message
     */
	function UpdateUser($iduser, $param, $value)
	{
		$result = UserClass::Update($iduser, $param, $value);
		return $result;
	}
	
	/**
	 * AddUserContact
	 *
	 * insert new user contact info
	 *
	 * @param	int			$iduser	user ID
	 * @param	int			$type	type of contact
	 * @param	int			$info	contact info
	 * return	int/string	$result	contact ID or error message	
	 */
	function AddUserContact($iduser, $type, $info) 
	{
		$result = UserClass::AddContact($iduser, $type, $info);
		return $result;
	}
	
	/**
	 * UpdateUserContact
	 *
	 * update user contact info
	 *
	 * @param	int		$idcontact	contact ID
	 * @param	string	$info		contact info
	 * return	string	$result		"successful" or error message	
	 */
	function UpdateUserContact($idcontact, $info) 
	{
		$result = UserClass::UpdateContact($idcontact, $info);
		return $result;
	}
	
	/**
	 * RemoveUserContact
	 *
	 * remove user contact
	 *
	 * @param	int		$idcontact	contact ID
	 * @return	string	$result		"successful" or error message	
	 */
	function RemoveUserContact($idcontact) 
	{
		$result = UserClass::RemoveContact($idcontact);
		return $result;
	}
	
	/**
	 * GetStaticticForUser
	 *
	 * returns a user statistic
	 *
	 * @param	int		$iduser		user ID
	 * @return	string	$mode		"by_year" or "by_month"
	 * @return	string	$year		year
	 * @return	string	$month		month
	 * @return	object	$result		user statistic	
	 */
	function GetStaticticForUser($iduser, $mode, $year, $month)
	{
		$user = new UserClass();
		$user->ReadFromDb($iduser);
		$user->GetStatistic($mode, $year, $month);
		return $user->obStatistic;
	}
	
	/**
	 * GetYear
	 *
	 * returns a list of years when they were created orders
	 *
	 * @return	array	$result	
	 */
	public function GetYear()
	{
		$sql = "SELECT DISTINCT creation AS label FROM press_track_new.order "
			 . "WHERE press_track_new.order.creation != ''";
		$query = mysql_query($sql);		
		
		$result = array();
		while ($date = mysql_fetch_object($query)) 
		{
			$ar = explode("/", $date->label);
			if (count($ar) > 2)
			{
				if (array_search($ar[2], $result, true) === false)
				{
					$result[] = $ar[2];
				}
			}
		}
		return $result;
	}
	
	/**
	 * GetOperation
	 *
	 * returns a list of operations
	 *
	 * @return	array	$result	
	 */
	public function GetOperation()
	{
		$sql = "SELECT idoperation FROM press_track_new.operation";
		$query = mysql_query($sql);
				
		while ($row = mysql_fetch_object($query)) 
		{ 
			$operation	= new OperationClass($row->idoperation);
			$result[]	= clone $operation;
		}				
		return $result;
	}
	
	/**
	 * GetPapers
	 *
	 * returns a list of papers
	 *
	 * @return	array	$result	
	 */
	public function GetPapers()
	{
		$sql = "SELECT idpaper FROM press_track_new.paper ORDER BY label, thick";
		$query = mysql_query($sql);
				
		while ($row = mysql_fetch_object($query)) 
		{
			$paper = new PaperClass();
			$paper->ReadFromDb($row->idpaper);
			$result[] = $paper;
		}				
		return $result;
	}
	
	/**
	 * GetRequestForPaper
	 *
	 * returns a request for paper
	 *
	 * @param	string	$table	"all_request" - for all request or "cur_request" - for current orders only
	 * @param	int		$year	filter request by year
	 * @return	array	$result	
	 */
	public function GetRequestForPaper($table, $year)
	{
		$result = PaperClass::GetRequestForPaper($table, $year);				
		return $result;
	}
	
	/**
	 * AddDelivery
	 *
	 * insert new delivery of paper
	 *
	 * :WARNING: 
	 *
	 * this method increases the number of paper
	 * and adds an entry in the table 'papers' if the table does
	 * not locate the paper as paper_label + paper_thick + paper_size 
	 *
	 * @param	string				$invoice		delivery label
	 * @param	string				$creation		delivery date
	 * @param	string				$paper_label	name of paper
	 * @param	int					$paper_thick	thickness of paper
	 * @param	string				$paper_size		width x height
	 * @param	int					$paper_num		the amount of paper in sheets
	 * @param	string				$supplier		paper supplier
	 * @param	string				$payer			printing press or the customer if the customer's paper
	 * @param	double				$sum			total amount
	 * @param	double				$cost			for update paper cost
	 * @return	AddDeliveryResultVO	$result	
	 */
	function AddDelivery($invoice, 
						 $creation, 
						 $paper_label, 
						 $paper_thick, 
						 $paper_size, 
						 $paper_num, 
						 $supplier, 
						 $payer, 
						 $sum, 
						 $cost) 
	{
		$paper = new PaperClass();
		$paper->SearchInDb($paper_label, $paper_thick, $paper_size);
		if ($paper->iPaperId == -1)
		{
			$paper->WriteToDb($paper_label, $paper_thick, $paper_size);
		}		
		$result = $paper->AddDelivery($invoice, $creation, $paper_num, $supplier, $payer, $sum);
		return $result;
	}
	
	/**
	 * UpdateDelivery
	 *
	 * update record about delivery of paper
	 *
	 * @param	int		$iddelivery	delivery ID
	 * @param	string	$param		delivery parameter
	 * @param	string	$value		value of parameter
	 * @return	string	$result		"successful" or error message
	 */
	function UpdateDelivery($iddelivery, $param, $value) 
	{
		$result = PaperClass::UpdateDelivery($iddelivery, $param, $value);
		return $result;
	}
	
	/**
	 * RemoveDelivery
	 *
	 * remove record about delivery of paper from database
	 *
	 * @param	int		$iddelivery	delivery ID
	 * @return	string	$result		"successful" or error message
	 */
	function RemoveDelivery($iddelivery)
    {
		$result = PaperClass::RemoveDelivery($iddelivery);
		return $result;			
	}
	
	function AddIssue($paper, 
					  $num, 
					  $cost, 
					  $creation, 
					  $request, 
					  $label)
	{
		$result = PaperClass::AddIssue($paper, $num, $cost, $creation, $request, $label);
		return $result;
	}
	
	function UpdateIssue($idissue, 
						 $paper, 
						 $creation, 
						 $cost, 
						 $num) 
	{	
		$result = PaperClass::UpdateIssue($idissue, $paper, $creation, $cost, $num);		
		return $result;
	}
	
	function UpdateIssueParam($idissue, $param, $value) 
	{
		$result = PaperClass::UpdateIssueParam($idissue, $param, $value);
		return $result;
	}
	
	function RemoveIssue($id)
    {
		$result = PaperClass::RemoveIssue($id);
		return $result; 
	}
	
	function GetIssue()
    {
		$sql = "SELECT *, 
			press_track_new.issue.idissue as idissue,
			press_track_new.issue.paper as paper,
			press_track_new.issue.num as num,
			press_track_new.issue.cost as cost,
			press_track_new.issue.creation as creation,
			press_track_new.issue.request as request,
			press_track_new.issue.label as label,
			press_track_new.paper.label as paper_label, 
			press_track_new.paper.thick as paper_thick, 
			press_track_new.paper.size as paper_size 
			FROM press_track_new.issue, press_track_new.paper WHERE press_track_new.paper.idpaper = press_track_new.issue.paper";
				
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
		{
			if ($row->request != null) {
				$sql = "SELECT press_track_new.user.name as customer FROM press_track_new.user 
					WHERE iduser = (SELECT press_track_new.order.customer FROM press_track_new.order 
					WHERE idorder = (SELECT press_track_new.task.order as idorder FROM press_track_new.task 
					WHERE press_track_new.task.idtask = $row->request))";
				$query2 = mysql_query($sql);
				$cust = mysql_fetch_object($query2);
				$row->customer = $cust->customer;
			}
			$result[] = $row;
		}
		return $result; 
	}
	
	/**
	 * GetPaperSuppliers
	 *	 
     * read a paper suppliers from database 
	 *
	 * @return	array	$result
     */
	function GetPaperSuppliers()
	{
		$result = PaperClass::GetSuppliers();
		return $result;
	}
	
	/**
	 * GetPaperPayers
	 *	 
     * read a paper payers from database 
	 *
	 * @return	array	$result
     */
	function GetPaperPayers()
	{
		$result = PaperClass::GetPayers();
		return $result;
	}
	
	/**
	 * GetGeneralReport
	 *	 
     * get a report for "general" section in Report module
	 *
	 * @return	object	$result
     */
	function GetGeneralReport($year, $month)
	{
		$result = ReportGeneralClass::GetGeneralReport($year, $month);
		return $result;
	}
	
	/**
	 * GetSaleReport
	 *	 
     * get a report for "sale" section in Report module
	 *
	 * @return	object	$result
     */
	function GetSaleReport($year)
	{
		$result = ReportSaleClass::GetSaleReport($year);
		return $result;
	}
	
	/**
	 * GetPaymentReport
	 *	 
     * get a report for "payment" section in Payment module
	 *
	 * @return	object	$result
     */
	function GetPaymentReport($year)
	{
		$result = ReportPaymentClass::GetPaymentReport($year);
		return $result;
	}
	
	/**
	 * GetOperationReport
	 *	 
     * get a report for "operation" section in Operation module
	 *
	 * @return	object	$result
     */
	function GetOperationReport($year, $section)
	{
		$result = ReportOperationClass::GetOperationReport($year, $section);
		return $result;
	}
	
	/**
	 * GetTracker
	 *	 
     * get a current order for tracker
	 *
	 * @return	GetTrackerResultVO	$result
     */
	function GetTracker()
	{
		set_time_limit(0);	
		$result = new GetTrackerResultVO();
		
		$sql = "SELECT idorder FROM press_track_new.order "
			 . "WHERE press_track_new.order.state != 4";
		$query = mysql_query($sql);	
		
		if (mysql_errno())
		{
			$result->message = mysql_errno() . ": " . mysql_error();
			return $result;
		}
		
		while ($ord = mysql_fetch_array($query)) 
		{
			$track 				= new TrackClass($ord[0]);
			$result->tracker[]	= clone $track;
		}
		$result->status = true;
		return $result;
	}
	
	/**
	 * GetPlans
	 *	 
     * get a planning for operation
	 *
	 * @return	GetPlanResultVO	$result
     */
	function GetPlan($operation)
    {
		switch ($operation)
		{
			case "press" :
				$plan = PressTargetClass::GetPlan();
			break;				
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*-----------------------------------------------------------------------------------> STATISTIC */
	
		
	function getTrack() 
	{
		set_time_limit(0);
		
		$sql = sprintf("SELECT label, section FROM press_track_new.operation ORDER BY section");
		$query = mysql_query($sql);		
		if (mysql_errno()) return mysql_errno() . " : " . mysql_error();
		while ($operation = mysql_fetch_object($query)) 
			$res->allOperations[] = $operation;
			
		$sql = sprintf("SELECT iduser AS iduser, name AS label 
			FROM press_track_new.user 
			WHERE medium = -1 AND section = 1 ORDER BY name");
		$query = mysql_query($sql);		
		if (mysql_errno()) return mysql_errno() . " : " . mysql_error();
		while ($manager = mysql_fetch_object($query)) 
			$res->allManagers[] = $manager;
			
		$sql = sprintf("SELECT iduser AS iduser, name AS label, medium AS medium 
			FROM press_track_new.user 
			WHERE medium > -1 ORDER BY name");
		$query = mysql_query($sql);		
		if (mysql_errno()) return mysql_errno() . " : " . mysql_error();
		while ($customer = mysql_fetch_object($query)) 
			$res->allCustomers[] = $customer;
		
		$sql = "SELECT idorder, label, group_num, manager, customer, name as manager_name
				FROM press_track_new.order, press_track_new.user 
				WHERE press_track_new.order.state != 4
				AND press_track_new.user.iduser = press_track_new.order.manager";				
		$query = mysql_query($sql);		
		if (mysql_errno()) return mysql_errno() . " : " . mysql_error();
		
		while ($order = mysql_fetch_object($query)) 
		{
			if ($order->customer != NULL)
			{
				$sql = "SELECT name as customer_name 
					FROM press_track_new.user 
					WHERE press_track_new.user.iduser = $order->customer";
				$query_cust = mysql_query($sql);
				if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
				
				while ($cust = mysql_fetch_object($query_cust)) 
					$order->customer_name = $cust->customer_name;
			}
			
			// собираем части заказа
			for ($g = 1; $g < $order->group_num + 1; $g++) 
			{
				$order->state_paper = 1;
				$order->state_prepress = 1;
				$order->state_press = 1;
				$order->state_postpress = 1;
				$order->state_destination  = 1;
						
				$part = $this->getPart($order->idorder, $g);
								
				$tsk_len = count($part->tasks);
				$rel_len = count($part->relations);
				$p_len = count($part->products);
					
				for($t_ind = 0; $t_ind < $tsk_len; $t_ind++) {
					$temp = array();
					for($r_ind = 0; $r_ind < $rel_len; $r_ind++) {
						if ($part->tasks[$t_ind]->idtask == $part->relations[$r_ind]->task_id) {
							for ($p_ind = 0; $p_ind < $p_len; $p_ind++) {
								if ($part->relations[$r_ind]->product_id == $part->products[$p_ind]->idproduct) {
									$temp[] = $part->products[$p_ind]->label;
								}
							}
						}
					}
					if ($p_len == count($temp))
						$part->tasks[$t_ind]->product = "для всех изделий";
					else
						$part->tasks[$t_ind]->product = implode(';', $temp);
						
					switch ($part->tasks[$t_ind]->section) {
						case 2 : 
						$part->tasks[$t_ind]->section_name = 'бумага';
						$part->tasks[$t_ind]->section_color = "#dddddd";
						break;
						case 3 : 
						$part->tasks[$t_ind]->section_name = 'препресс'; 
						$part->tasks[$t_ind]->section_color = "#FAEC0C";
						break;
						case 4 : 
						$part->tasks[$t_ind]->section_name = 'печать'; 
						$part->tasks[$t_ind]->section_color = "#2e93fb";
						break;
						case 5 : 
						$part->tasks[$t_ind]->section_name = 'постпечать';
						$part->tasks[$t_ind]->section_color = "#05fb16";
						break;
						case 6 : 
						$part->tasks[$t_ind]->section_name = 'отгрузка'; 
						$part->tasks[$t_ind]->section_color = "#05fbaa";
						break;
					}
					
					switch ($part->tasks[$t_ind]->state) {
						case 1 : 
						$part->tasks[$t_ind]->state_color = "#ffffff";
						break;
						case 3 : 
						$part->tasks[$t_ind]->state_color = "#2e93fb";
						break;
						case 5 : 
						$part->tasks[$t_ind]->state_color = "#fd0410";
						break;
						case 4 : 
						$part->tasks[$t_ind]->state_color = "#05fb16";
						break;
						default:
						$part->tasks[$t_ind]->state_color = "#ffffff";
						break;
					}					
					
					$part->tasks[$t_ind]->order_label = $order->label;
					$part->tasks[$t_ind]->manager_name = $order->manager_name;
					$part->tasks[$t_ind]->customer_name = $order->customer_name;
					$part->tasks[$t_ind]->value = strtr($part->tasks[$t_ind]->value, "\r", ";");
					
					//$ArrayOfTrack[] = $part->tasks[$t_ind];
				}			
				$order->tasks = $part->tasks;
				$part = null;
				$ArrayOfTrack[] = clone $order;
				
			}			
		}			
		$res->track = $ArrayOfTrack;		
		return $res;
	}	

	function updateTarget($idtarget, $day, $time, $length, $note)
    {
		$sql = sprintf("UPDATE target 
			SET day = '%s', time = '%s', length = %d, note = '%s' 
			WHERE idtarget = %d", $day, $time, $length, $note, $idtarget); 			 
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";
	}
	
	function updateTargetLen($idtask)
    {
		$sql = "SELECT * FROM target WHERE task = $idtask LIMIT 1"; 
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		$trg = mysql_fetch_object($query);
		if($trg->day == "-/-" || $trg->time == "--:--")
		{		
			$target_len = 20;
			$sql = "SELECT * FROM task WHERE idtask = $idtask LIMIT 1"; 
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$tsk = mysql_fetch_object($query);		
		
			switch($tsk->label)
			{
			case "вывод форм" : 
				$temp = explode("\r", $tsk->value);
				$form_num = str_replace("форм : ", "", $temp[0]);
				if($form_num > 4) $target_len = ($form_num / 4) * 20;
			break;
			case "печать" :
				$temp = explode("\r", $tsk->value);
				$press_label = trim(str_replace("машина : ", "", $temp[0]));
				$press_run = trim(str_replace("тираж : ", "", $temp[1]));
				$press_run = trim(str_replace(" ", "", $press_run));
				$press_run = trim(str_replace("c/c", "", $press_run));
				$press_color = trim(str_replace("красочность : ", "", $temp[4]));
				$total_run = 0;
				$temp2 = explode(",", $press_run);
				foreach($temp2 as $r)
				{
					$temp3 = explode("x", $r);
					if(count($temp3) == 2)
						$total_run = $total_run + ($temp3[0] * $temp3[1]);
					else
						$total_run = $total_run + $temp3[0];
				}
				
				if($total_run <= 500)
					$target_len = 20;
				else if($total_run <= 1000)
					$target_len = 30;
				else if($total_run <= 2000)
					$target_len = 40;
				else if($total_run <= 3000)
					$target_len = 50;
				else if($total_run <= 5000)
					$target_len = 60;
				else if($total_run <= 10000)
					$target_len = 150;
				$target_len = $target_len + 10;
			break;
			}
			$sql = sprintf("UPDATE target SET length = %d WHERE idtarget = %d", 
				$target_len, $trg->idtarget); 			 
			$query = mysql_query($sql);
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			else return "successful";
		}
	}	
	
	
	function getPaper($idpaper)
	{
		if($idpaper == -1)
			$sql = "SELECT * FROM press_track_new.paper ORDER BY label, thick";
		else
			$sql = sprintf("SELECT * FROM press_track_new.paper WHERE idpaper = %d", $idpaper);
		
		$query = mysql_query($sql);	
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
			$ar[] = $row;
		return $ar;
	}
	
	function updatePaper($idpaper, $param, $value) 
	{
		if ($param == "cost" || $param == "thick")
		{
			$sql = sprintf("UPDATE press_track_new.paper 
				SET %s = %f WHERE idpaper = %d LIMIT 1", $param, $value, $idpaper);
		}
		else if ($param == "total")
		{
			$sql = sprintf("UPDATE press_track_new.paper 
				SET press_track_new.paper.total = %d 
				WHERE idpaper = %d LIMIT 1", $value, $idpaper);
		}
		else if ($param == "add")
		{
			$sql = "UPDATE press_track_new.paper 
				SET press_track_new.paper.total = press_track_new.paper.total + $value 
				WHERE press_track_new.paper.idpaper = $idpaper LIMIT 1";
		}
		else
			$sql = sprintf("UPDATE press_track_new.paper SET %s = '%s' WHERE idpaper = %d LIMIT 1", $param, $value, $idpaper);
		$query = mysql_query($sql);
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		else return "successful";	
	}
	
	function correctPaper($idpaper, $value, $label, $creation) 
	{
		$sql = sprintf("SELECT total AS cur_total 
			FROM press_track_new.paper 
			WHERE idpaper = %d", $idpaper);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			$result->status = false;
			$result->message = mysql_errno() . ": " . mysql_error();
			return $result;
		}
		
		$res = mysql_fetch_object($query);
		if ($value > $res->cur_total) {
			$sql = sprintf("INSERT INTO press_track_new.delivery (
				press_track_new.delivery.paper, 
				press_track_new.delivery.num, 
				press_track_new.delivery.creation, 
				press_track_new.delivery.invoice, 
				press_track_new.delivery.supplier) 
				VALUES (%d, %d, '%s', '%s', '%s')", 
				$idpaper, $value - $res->cur_total, $creation, $label." (".$res->cur_total." : ".$value.")", $label." (".$res->cur_total." : ".$value.")");
			$query = mysql_query($sql);	
			$iddelivery = mysql_insert_id();
			$sql = sprintf("SELECT * FROM delivery WHERE iddelivery = %d", $iddelivery);
			$query = mysql_query($sql);
			$result->delivery = mysql_fetch_object($query);
			
		}
		else if ($value < $res->cur_total) {
			$sql = sprintf("INSERT INTO press_track_new.issue (
				press_track_new.issue.paper, 
				press_track_new.issue.num, 
				press_track_new.issue.creation, 
				press_track_new.issue.label) 
				VALUES (%d, %d, '%s', '%s')", 
				$idpaper, $res->cur_total - $value, $creation, $label." (".$res->cur_total." : ".$value.")");
			$query = mysql_query($sql);	
			$idissue = mysql_insert_id();
			$sql = sprintf("SELECT * FROM issue WHERE idissue = %d", $idissue);
			$query = mysql_query($sql);
			$result->issue = mysql_fetch_object($query);
		}
				
		$sql = sprintf("UPDATE press_track_new.paper 
			SET press_track_new.paper.total = %d 
			WHERE idpaper = %d", $value, $idpaper);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			$result->status = false;
			$result->message = mysql_errno() . ": " . mysql_error();
			return $result;
		}
		
		$result->status = true;
		return $result;
	}
		
	function getOperationByCustomer($year, $month, $operation, $section) {
		set_time_limit(0);
		
		// выбираем всех заказчиков
		$sql = sprintf("SELECT DISTINCT customer AS iduser, user.name AS name FROM press_track_new.order, press_track_new.user 
			WHERE LOCATE('%s', press_track_new.order.creation, 3) AND iduser = customer", $month . "/" . $year);
						
		$query = mysql_query($sql);		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		// собираем общую стоимость операции с названием $operation по мес за год $year
		while ($customer = mysql_fetch_object($query)) 
		{
			if ($section != 4) {
				$sql = sprintf("SELECT SUM(cost) AS total FROM task 
					WHERE label = '%s' 
					AND task.order IN
					(SELECT idorder FROM press_track_new.order 
					WHERE LOCATE('%s', press_track_new.order.creation, 3)
					AND press_track_new.order.customer = %d)", $operation, $month . "/" . $year, $customer->iduser);
			}
			else {
				$data = $month . '/' . $year;
				$sql = "SELECT SUM(cost) AS total FROM task 
					WHERE section = 4
					AND value LIKE '%$operation%'
					AND task.order IN
					(SELECT idorder FROM press_track_new.order 
					WHERE creation LIKE '%$data'
					AND press_track_new.order.customer = $customer->iduser)";
			}
			$query3 = mysql_query($sql);
				
			if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
			$row = mysql_fetch_object($query3);
			if ($row->total > 0) {
				$customer->total = (int)$row->total;
				$ArrayOfCustomer[] = $customer;
			}
		}
		return $ArrayOfCustomer;
	}
	
	function getData($manager_id, $table)
    {
		$ArrayOfData = array();
		switch ($table)
		{
			case "manager":
			{
				$sql = sprintf("SELECT * FROM press_track_new.user WHERE medium = -1 AND section = 1 ORDER BY name");
			} break;
			case "customer":
			{
				$sql = "SELECT * FROM press_track_new.user WHERE press_track_new.user.medium = $manager_id ORDER BY name";
			} break;
			case "product":
			{
				$sql = "SELECT * FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id";
				$query = mysql_query($sql);
				$ArrayOfData = array();
				while ($row = mysql_fetch_object($query)) 
				{
					$sql = "SELECT * FROM press_track_new.product WHERE press_track_new.product.order = $row->idorder";
					$query2 = mysql_query($sql);
					while ($row2 = mysql_fetch_object($query2)) 
					{
						$ArrayOfData[] = $row2;
					}
				}
				return $ArrayOfData;
			}break;
			case "task":
			{
				$sql = "SELECT * FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id";
				$query = mysql_query($sql);
				$ArrayOfData = array();
				while ($row = mysql_fetch_object($query)) 
				{
					$sql = "SELECT * FROM press_track_new.task WHERE press_track_new.task.order = $row->idorder";
					$query2 = mysql_query($sql);
					while ($row2 = mysql_fetch_object($query2)) 
					{
						$ArrayOfData[] = $row2;
					}
				}
				return $ArrayOfData;
			}break;
			case "relation":
			{
				$sql = "SELECT * FROM press_track_new.relation WHERE press_track_new.relation.product_id IN  (
				SELECT idproduct FROM press_track_new.product WHERE press_track_new.product.order IN (
				SELECT idorder FROM press_track_new.order WHERE press_track_new.order.manager = $manager_id))";
				$query = mysql_query($sql);
				while ($row = mysql_fetch_object($query)) 
				{
					$ArrayOfData[] = $row;
				}
				return $ArrayOfData;
			}break;
			case "payment":
			{
				$sql = "SELECT *, label, name FROM press_track_new.payment, press_track_new.order, press_track_new.user WHERE press_track_new.order.idorder = press_track_new.payment.order AND press_track_new.payment.manager = $manager_id AND press_track_new.user.iduser = press_track_new.payment.customer";
			} break;
			case 'user_name':
			{
				$sql = sprintf("SELECT name as val FROM press_track_new.user WHERE iduser = %d", $manager_id);
				$query = mysql_query($sql);
				$row = mysql_fetch_object($query);
				return $row->val;
			}break;
			default:
			{
				$sql = "SELECT * FROM press_track_new." . $table;
			}
		}

		$query = mysql_query($sql);
		
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		
		while ($row = mysql_fetch_object($query)) 
      	{
			$ArrayOfData[] = $row;
	  	}
		return $ArrayOfData;
	}	
	
	////
	
	function insertOperation($label, $section)
    {
		$sql = sprintf("INSERT INTO operation (label, section) VALUES ('%s', '%d')", $label, $section);
		$query = mysql_query($sql);
		$operation_id = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return $operation_id;
	}

	function insertFactor($f)
    	{
		$sql = sprintf("INSERT INTO press_track_new.factor (press_track_new.factor.label, press_track_new.factor.value, press_track_new.factor.operation) VALUES ('%s', '%s', %d)", $f->label, $f->value, $f->operation);
		$query = mysql_query($sql);
		$factor_id = mysql_insert_id(); 
		if (mysql_errno()) return mysql_errno() . ": " . mysql_error();
		return $factor_id;
	}		
		
		
		
	/**
	 * @param 'тираж' @param 'формат изделия' @param 'бумага г/м2' @param 'красочность' @param 'кол-во сгибов'
	 */
	function newOrderMaster($run, $pr_size, $paper_thick, $color_num, $fold_num){
		$MIN_FIT = 10;
		$SHEET_MIN = 100;
		
		$COST_OF_SHIFT = 20000;
		$MIN_IN_SHIFT = 600;
		
		$P_WIDTH = 47;
		$P_HEIGHT = 65;		
		$CUT_PART = 2;		
		$PS_WIDTH = ($P_WIDTH * 10) - 10;
		$PS_HEIGHT = ( ($P_HEIGHT / $CUT_PART) * 10 ) - 10;
		
		$ar_pr_size = explode("x", str_replace("_", "", $pr_size));
		$temp1 = (int)($PS_WIDTH / $ar_pr_size[0]) * (int)($PS_HEIGHT  / $ar_pr_size[1]);
		$temp2 = (int)($PS_WIDTH / $ar_pr_size[1]) * (int)($PS_HEIGHT / $ar_pr_size[0]);
		$product_num = ($temp1 >= $temp2) ? (int) $temp1 : (int) $temp2;
		$press_sheet_run = $run / $product_num;
		
		// ctp
		$ar_form_num = explode("+", str_replace("_", "", $color_num));	
		$ctp_cost = $ar_form_num[0] * 170;
		$ctp_cost = $ctp_cost + ($ar_form_num[1] * 170);
		
		// paper
		$press_waste = 300;
		if ($press_sheet_run <= 500)
		{
			if($ar_form_num == 1)
				$press_waste = 100;
			else if($ar_form_num <= 4)
				$press_waste = 200;
			else if($ar_form_num >= 8)
				$press_waste = 300;
			if ($fold_num > 0)
				$press_waste = $press_waste + 50;
		}
		else if ($press_sheet_run <= 1000)
		{
			if($ar_form_num == 1)
				$press_waste = 150;
			else if($ar_form_num <= 4)
				$press_waste = 200;
			else if($ar_form_num >= 8)
				$press_waste = 300;
			if ($fold_num > 0)
				$press_waste = $press_waste + 100;
		}
		else if ($press_sheet_run <= 2000)
		{
			if($ar_form_num == 1)
				$press_waste = 200;
			else if($ar_form_num <= 4)
				$press_waste = 250;
			else if($ar_form_num >= 8)
				$press_waste = 400;
			if ($fold_num > 0)
				$press_waste = $press_waste + 150;
		}
		else if ($press_sheet_run <= 3000)
		{
			if($ar_form_num == 1)
				$press_waste = 200;
			else if($ar_form_num <= 4)
				$press_waste = 300;
			else if($ar_form_num >= 8)
				$press_waste = 400;
			if ($fold_num > 0)
				$press_waste = $press_waste + 150;
		}
		else if ($press_sheet_run <= 5000)
		{
			if($ar_form_num == 1)
				$press_waste = 250;
			else if($ar_form_num <= 4)
				$press_waste = 300;
			else if($ar_form_num >= 8)
				$press_waste = 500;
			if ($fold_num > 0)
				$press_waste = $press_waste + 200;
		}
		else if ($press_sheet_run <= 10000)
		{
			if($ar_form_num == 1)
				$press_waste = 300;
			else if($ar_form_num <= 4)
				$press_waste = 400;
			else if($ar_form_num >= 8)
				$press_waste = 600;
			if ($fold_num > 0)
				$press_waste = $press_waste + 300;
		}
		else if ($press_sheet_run <= 20000)
		{
			if($ar_form_num == 1)
				$press_waste = 500;
			else if($ar_form_num <= 4)
				$press_waste = 600;
			else if($ar_form_num >= 8)
				$press_waste = 800;
			if ($fold_num > 0)
				$press_waste = $press_waste + 400;
		}
		else if ($press_sheet_run > 20000)
		{
			if($ar_form_num == 1)
				$press_waste = 600;
			else if($ar_form_num <= 4)
				$press_waste = 800;
			else if($ar_form_num >= 8)
				$press_waste = 1500;
			if ($fold_num > 0)
				$press_waste = $press_waste + 500;
		}
		
		$paper_weight = ((($P_WIDTH / 100) * ($P_HEIGHT / 100) * $paper_thick) / 1000) * (($press_sheet_run + $press_waste) / $CUT_PART);
		$paper_cost = (48000 / 1000) * $paper_weight;
		
		// press
		$fit_num = ($ar_form_num[1] != 0) ? 2 : 1;
		$press_time = $MIN_FIT * $fit_num;
		$press_time = $press_time + ($press_sheet_run / $SHEET_MIN);
		
		// закладка бумаги
		if ($paper_thick <= 105)
		{
			$num_of_paper_zak = (int)($press_sheet_run / 3300);
			$r = 0;
			if ($num_of_paper_zak < 1)
			{
				$num_of_paper_zak = 1;
			}
			else if ($press_sheet_run % 3300 > 0)
			{
				$r = 1;
			}
			$paper_time =  (int)(10 * ($num_of_paper_zak + $r));
		}
		else if ($paper_thick <= 115)
		{
			$num_of_paper_zak = (int)($press_sheet_run / 3000);
			if ($num_of_paper_zak < 1)
			{
				$num_of_paper_zak = 1;
			}
			else if ($press_sheet_run % 3000 > 0)
			{
				$r = 1;
			}
			$paper_time =  (int)(10 * ($num_of_paper_zak + $r));
		}
		else if ($paper_thick <= 150)
		{
			$num_of_paper_zak = (int)($press_sheet_run / 2700);
			if ($num_of_paper_zak < 1)
			{
				$num_of_paper_zak = 1;
			}
			else if ($press_sheet_run % 2700 > 0)
			{
				$r = 1;
			}
			$paper_time =  (int)(10 * ($num_of_paper_zak + $r));
		}
		else if ($paper_thick >= 170)
		{
			$num_of_paper_zak = (int)($press_sheet_run / 2500);
			if ($num_of_paper_zak < 1)
			{
				$num_of_paper_zak = 1;
			}
			else if ($press_sheet_run % 2500 > 0)
			{
				$r = 1;
			}
			$paper_time =  (int)(10 * ($num_of_paper_zak + $r));
		}
		
		if ($press_time < 600)
		{
			$COST_OF_SHIFT = (1200 - $press_time) / 0.03;
		}
		$press_cost = (($press_time + $paper_time) * ($COST_OF_SHIFT / $MIN_IN_SHIFT));
		
		// фальцовка
		$fold_cost = ($fold_num > 0) ? (300 + (0.08 * ($fold_num * $run))) : 0;
		
		return "--- ЗАКАЗ ---" .
				"\rтираж по печати : " . $press_sheet_run .
				"\rвремя закладки бумаги : " . $paper_time .
				"\rвремя печати : " . $press_time .
				"\rбумага - кол-во на печать 47х65 : " . ($press_sheet_run / $CUT_PART) .
				"\rбумага - кол-во на приладку 465х320 : " . $press_waste .
				"\rбумага - вес : " . $paper_weight .
				"\r--- СТОИМОСТЬ ---" .
				"\rстоимость смены : " . round($COST_OF_SHIFT, 2) .
				"\rстоимость минуты : " . round(($COST_OF_SHIFT / $MIN_IN_SHIFT), 2) .
				"\rпечать : " . round($press_cost, 2) . 
				"\rформы : " . $ctp_cost . 
				"\rбумага : " . $paper_cost . 
				"\rфальцовка : " . $fold_cost . 
				"\r\rитого : " . round(($press_cost + $paper_cost + $ctp_cost), 2);
	}
	
	/**
	* calculate cost of magazine
	* @param	e.g. 1000
	* @param	e.g. 210
	* @param	e.g. 297
	* @param	without cover - e.g. 16
	* @param	e.g. 115
	* @param	e.g. _4+4
	* @param	e.g. 105
	* @param	e.g. _1+1
	*/
	function CostOfMagazine($run, $page_width, $page_height, $num_of_page,
							$paper_thick_for_cover, $color_num_for_cover,
							$paper_thick_for_block, $color_num_for_block)
	{
		$PAPER_WIDTH	= 47;
		$PAPER_HEIGHT	= 65;		
		$PAPER_CUT_PART = 2;	

		$TIME_OF_ONE_FIT = 10;
		$NUM_OF_SHEET_IN_MINUTE = 100;
		
		$COST_OF_SHIFT = 20000;
		$MINUTE_IN_SHIFT = 600;
		
		$PRESS_SHEET_WIDTH 	= ($PAPER_WIDTH * 10) - 10;
		$PRESS_SHEET_HEIGHT = (($PAPER_HEIGHT / $PAPER_CUT_PART) * 10) - 10;
		
		// run for cover press_sheet
		$variant1 = (int)($PRESS_SHEET_WIDTH / ($page_width * 2)) * (int)($PRESS_SHEET_HEIGHT  / $page_height);
		$variant2 = (int)($PRESS_SHEET_WIDTH / $page_height) * (int)($PRESS_SHEET_HEIGHT / ($page_width * 2));
		$NumOfProduct = ($variant1 >= $variant2) ? (int) $variant1 : (int) $variant2;
		$RunOfCoverPressSheet = $run / $NumOfProduct;
		
		// run for block press_sheet
		$NumOfBlockSpreads = ($num_of_page / 4)  / $NumOfProduct;
		$RunOfBlockPressSheet = $RunOfCoverPressSheet * $NumOfBlockSpreads;
		
		// COST OF CTP
		$arFormNumCover = explode("+", str_replace("_", "", $color_num_for_cover));	
		$CostOfCtpCover = $arFormNumCover[0] * 170;
		$CostOfCtpCover = $CostOfCtpCover + ($arFormNumCover[1] * 170);
		
		$arFormNumBlock = explode("+", str_replace("_", "", $color_num_for_block));	
		$CostOfCtpBlock = $arFormNumBlock[0] * 170;
		$CostOfCtpBlock = $CostOfCtpBlock + ($arFormNumBlock[1] * 170);
		$CostOfCtpBlock = $CostOfCtpBlock * $NumOfBlockSpreads;
		
		// PAPER FOR COVER
		$WasteForCover = $this->getWaste($RunOfCoverPressSheet, ($arFormNumCover[0] + $arFormNumCover[1]));
		$WeightOfPaperForCover = ((($PAPER_WIDTH / 100) * ($PAPER_HEIGHT / 100) * $paper_thick_for_cover) / 1000) * (($RunOfCoverPressSheet + $WasteForCover) / $PAPER_CUT_PART);
		$CostOfPaperCover = (48000 / 1000) * $WeightOfPaperForCover;
		
		// PAPER FOR BLOCK
		$WasteForBlock = $this->getWaste($RunOfBlockPressSheet, ($arFormNumBlock[0] + $arFormNumBlock[1]));
		$WeightOfPaperForBlock = ((($PAPER_WIDTH / 100) * ($PAPER_HEIGHT / 100) * $paper_thick_for_block) / 1000) * (($RunOfBlockPressSheet + $WasteForBlock) / $PAPER_CUT_PART);
		$CostOfPaperBlock = (48000 / 1000) * $WeightOfPaperForBlock;
		
		// FIT 
		$NumOfFitCover 	= ($arFormNumCover[1] != 0) ? 2 : 1;
		$NumOfFitBlock 	= ($arFormNumBlock[1] != 0) ? 2 : 1;
		$NumOfFitBlock 	= $NumOfFitBlock * $NumOfBlockSpreads;
		$NumOfFitTotal 	= $NumOfFitCover + $NumOfFitBlock;
		$TimeOfFit 		= $NumOfFitTotal * $TIME_OF_ONE_FIT;
		
		// PRESS
		$TimeOfPress = $TimeOfFit + ($RunOfCoverPressSheet / $NUM_OF_SHEET_IN_MINUTE);
		$TimeOfPress = $TimeOfPress + ($RunOfBlockPressSheet / $NUM_OF_SHEET_IN_MINUTE);
		
		if ($TimeOfPress < 600)
		{
			$COST_OF_SHIFT = (1200 - $TimeOfPress) / 0.03;
		}
		$CostOfPress = ($TimeOfPress * ($COST_OF_SHIFT / $MINUTE_IN_SHIFT));
		
		// COLLATE
		$NumOfCollate = (int) ($num_of_page / 4) / 16;
		if ($NumOfCollate > 1)
		{
			$NumOfCollate = 1;
		}
		$СostOfCollate = 600 + ($NumOfCollate * 0.08);
		
		return "\rтираж на печать обложки : " . $RunOfCoverPressSheet . 
			   "\rтираж на печать блока   : " . $NumOfBlockSpreads . " x " . $RunOfCoverPressSheet .
			   "\rкол-во приладок на печать обложки : " . $NumOfFitCover .
			   "\rкол-во приладок на печать блока : " . $NumOfFitBlock .
			   "\rобщее время на печать : " . $TimeOfPress .
			   "\rкол-во закладок : " . $NumOfCollate .
			   "\r\r--------СТОИМОСТЬ-------- " . 
			   "\rцена форм для обложки   : " . $CostOfCtpCover .
			   "\rцена форм для блока     : " . $CostOfCtpBlock .
			   "\rцена бумаги для обложки : " . $CostOfPaperCover .
			   "\rцена бумаги для блока   : " . $CostOfPaperBlock .
			   "\rцена печати   : " . $CostOfPress .
			   "\rцена сборки   : " . $СostOfCollate . 
			   "\r\rИТОГО : " . 
			   ($CostOfCtpCover + 
			   $CostOfCtpBlock + 
			   $CostOfPaperCover + 
			   $CostOfPaperBlock +
			   $CostOfPress + 
			   $СostOfCollate);
	}
	
	function getWaste($run, $color_num)
	{
		$w = 300;
		if ($r <= 500)
		{
			if($color_num == 1)
				$w = 100;
			else if($color_num <= 4)
				$w = 200;
			else if($color_num >= 8)
				$w = 300;			
		}
		else if ($r <= 1000)
		{
			if($color_num == 1)
				$w = 150;
			else if($color_num <= 4)
				$w = 200;
			else if($color_num >= 8)
				$w = 300;
		}
		else if ($r <= 2000)
		{
			if($color_num == 1)
				$w = 200;
			else if($color_num <= 4)
				$w = 250;
			else if($color_num >= 8)
				$w = 400;
		}
		else if ($r <= 3000)
		{
			if($color_num == 1)
				$w = 200;
			else if($color_num <= 4)
				$w = 300;
			else if($color_num >= 8)
				$w = 400;
		}
		else if ($r <= 5000)
		{
			if($color_num == 1)
				$w = 250;
			else if($color_num <= 4)
				$w = 300;
			else if($color_num >= 8)
				$w = 500;
		}
		else if ($r <= 10000)
		{
			if($color_num == 1)
				$w = 300;
			else if($color_num <= 4)
				$w = 400;
			else if($color_num >= 8)
				$w = 600;
		}
		else if ($r <= 20000)
		{
			if($color_num == 1)
				$w = 500;
			else if($color_num <= 4)
				$w = 600;
			else if($color_num >= 8)
				$w = 800;
		}
		else if ($r > 20000)
		{
			if($color_num == 1)
				$w = 600;
			else if($color_num <= 4)
				$w = 800;
			else if($color_num >= 8)
				$w = 1500;
		}
		return w;
	}
	
	function test()
	{
		$data = "02/2011";
		$sql = "SELECT idorder FROM press_track_new.order WHERE creation LIKE '%$data'";
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		
		$arr_of_orders = array();
		while ($row = mysql_fetch_array($query)) 
		{
			$arr_of_orders[] = $row[0];  
		}
		
		$sql = "SELECT SUM(cost) FROM task 
			WHERE task.order IN (".implode(',', $arr_of_orders).")";
		$query = mysql_query($sql);		
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		while ($row = mysql_fetch_array($query)) 
		{
			$arr_of_cost[] = $row[0];  
		}
		return $arr_of_cost;
	}
}
?>